package com.xl.rentkeeper.business;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.xl.fuse.protos.heartbeat.KeepAlive;
import com.xl.rentkeeper.App;

/**
 * Created by zwc on 2015/7/9.
 */
public class ConfigLogic {
    public static ConfigLogic getInstance() {
        return (ConfigLogic) SingletonRegistry.getInstance(ConfigLogic.class);
    }

    private static  final String Key_Local_Config = "key_local_config";
    LocalConfig configs = new LocalConfig();
    static class LocalConfig {
        public long lastSyncServerTs = System.currentTimeMillis() / 1000;
        public long lastClientTs = System.currentTimeMillis() / 1000;
    }

    private ConfigLogic() {
        String p = App.getApp().getSp().getString(Key_Local_Config,"");
        if (!TextUtils.isEmpty(p)) {
            try {
                LocalConfig configs = new Gson().fromJson(p,LocalConfig.class);
                this.configs = configs;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public long getServerTs() {
        long ts = System.currentTimeMillis() / 1000 + (configs.lastSyncServerTs - configs.lastClientTs);
        return ts;
    }

    public void saveServerTs(KeepAlive send,KeepAlive recv) {
        configs.lastSyncServerTs = recv.ts + (System.currentTimeMillis() / 1000 - send.ts) / 2;
        configs.lastClientTs = System.currentTimeMillis() / 1000;
        App.getApp().getSp().edit().putString("test",new Gson().toJson(configs)).commit();
    }
}
